package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.sms.CodeUtil;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void getCode(String phone) {
        //验证码的key
        String codeKey = RedisConstant.APP_LOGIN_PREFIX + phone;
        //防止前端频繁发送验证码，判断redis中是否含有指定的codeKey
        Boolean result = redisTemplate.hasKey(codeKey);
        if (result) {//如果存在，则不能再发送验证码
            //redis验证码还剩多长时间过期
            Long expireTime = redisTemplate.getExpire(codeKey);
            //验证码总共的有效时间
            Integer totalTime = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            if (totalTime - expireTime < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        //生成验证码
        String code = CodeUtil.getCode(6);
        //发送验证码
        smsService.sendCode(phone, code);

        //redis存储验证码
        redisTemplate.opsForValue().set(codeKey, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        String code = loginVo.getCode();

        String phone = loginVo.getPhone();

        //验证码的key
        String codeKey = RedisConstant.APP_LOGIN_PREFIX + phone;

        //判断为空信息
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (!StringUtils.hasText(code)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        //验证redis中的验证码是否过期

        //获取redis中存储的验证码
        String redisCode = redisTemplate.opsForValue().get(codeKey);

        if (!StringUtils.hasText(redisCode)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        //验证验证码是否正确
        if (!code.equals(redisCode)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //查询用户信息是否存在于数据库中
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
        if (userInfo == null) {//如果用户不存在，那我们就自动注册一个新用户
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户" + phone.substring(6));
            userInfoMapper.insert(userInfo);//插入用户信息
        }
        //判断用户是否被禁用
        if (userInfo.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //生成token
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }


}
